package com.sgj.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgj.mapper.UserMapper;
import com.sgj.entity.User;
import com.sgj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author 沈国纪
 * @date 2021/12/11 18:53
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Override
	public void register(User user) {
		// 查询是否已存在用户
		User user1 = baseMapper.selectByName(user.getUsername());
		if (Objects.nonNull(user1)) {
			throw new RuntimeException("该用户名已被注册");
		}
		// 密码进行加密处理  md5 + salt + hash 散列
		// 生产随机盐
		String salt = RandomUtil.randomString(8);
		Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
		user.setSalt(salt);
		user.setPassword(md5Hash.toHex());
		baseMapper.insert(user);
	}

	@Override
	public User findByUsername(String username) {
		return baseMapper.selectByName(username);
	}

	@Override
	public User findRolesByUserId(Integer id) {
		return baseMapper.findRolesByUserId(id);
	}
}